package cn.libinal.scloud.base.oauth.config;

import cn.libinal.scloud.base.oauth.security.UserDetailsServiceImpl;
import cn.libinal.scloud.base.oauth.security.handler.LoginFailureHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author libinal
 * created at 2018/11/4 14:01
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserDetailsServiceImpl userDetailsService;

    private final LoginFailureHandler loginFailureHandler;

    public WebSecurityConfig(UserDetailsServiceImpl userDetailsService, LoginFailureHandler loginFailureHandler) {
        this.userDetailsService = userDetailsService;
        this.loginFailureHandler = loginFailureHandler;
    }

    /**
     * 加密方式
     * @return 加密类型
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }



    @Override
    public void configure(WebSecurity web) throws Exception {
        web
                .ignoring().antMatchers("/css/**", "/js/**",
                "/plugins/**", "/favicon.ico");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .requestMatchers().antMatchers("/auth/login", "/auth/authorize", "/oauth/authorize")
                .and()
                .authorizeRequests()
                .antMatchers("/auth/login", "/auth/authorize","/oauth/authorize").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().failureHandler(loginFailureHandler)
                .loginPage("/auth/login").loginProcessingUrl("/auth/authorize")
                .and()
                .httpBasic().disable();
    }
}
